package com.fysports.framework.kit.security;

import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.fysports.web.config.AppConst;
import com.fysports.web.kit.commons.StringKit;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;


/**
 * Created by konbluesky
 * Date : 14-8-2 上午9:06
 * Project : JdmData_WebServer
 * 依赖jar包
 * <dependency>
 * <groupId>org.bouncycastle</groupId>
 * <artifactId>bcprov-ext-jdk15on</artifactId>
 * <version>1.50</version>
 * </dependency>
 * <dependency>
 * <groupId>org.bouncycastle</groupId>
 * <artifactId>bcprov-jdk15on</artifactId>
 * <version>1.50</version>
 * </dependency>
 */
public class IDEASecurityKit {
    @SuppressWarnings("unused") private static Log log = Log.getLog(IDEASecurityKit.class);

    /**
     * 密钥算法
     */
    public static final String KEY_ALGORITHM = "IDEA";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     */
    public static final String CIPHER_ALGORITHM = "IDEA/ECB/PKCS5Padding";

    static {
        // 加入BouncyCastleProvider支持

        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 转换密钥
     *
     * @param key 二进制密钥
     * @return Key 密钥
     * @throws Exception
     */
    private static Key toKey(byte[] key) throws Exception {
        // 生成秘密密钥

        SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);

        return secretKey;
    }


    /**
     * 加密 <br/>
     * 密钥：AppConfig.getParamMapValue(AppConst.SECURITY_IDEAKEY)
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data) throws Exception {
        String securityKey = PropKit.use(AppConst.CONFIG_SYSTEM).get(AppConst.SECURITY_IDEAKEY);
        byte[] keyByte = StringKit.decodeBase64(securityKey);
        return encrypt(data, keyByte);
    }


    /**
     * 解密 <br/>
     * 密钥：AppConfig.getParamMapValue(AppConst.SECURITY_IDEAKEY)
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data) throws Exception {
        String securityKey = PropKit.use(AppConst.CONFIG_SYSTEM).get(AppConst.SECURITY_IDEAKEY);
        byte[] keyByte = StringKit.decodeBase64(securityKey);
        return decrypt(data, keyByte);
    }


    /**
     * 解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 还原密钥

        Key k = toKey(key);

        // 实例化

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        // 初始化，设置为解密模式

        cipher.init(Cipher.DECRYPT_MODE, k);

        // 执行操作

        return cipher.doFinal(data);
    }


    /**
     * 加密
     *
     * @param data 待加密数据
     * @param key  密钥
     * @return byte[] 加密数据
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 还原密钥

        Key k = toKey(key);

        // 实例化

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        // 初始化，设置为加密模式

        cipher.init(Cipher.ENCRYPT_MODE, k);

        // 执行操作

        return cipher.doFinal(data);
    }


    /**
     * 生成密钥 <br>
     *
     * @return byte[] 二进制密钥
     * @throws Exception
     */
    public static byte[] initKey() throws Exception {
        // 实例化

        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);

        // 初始化

        kg.init(128);

        // 生成秘密密钥

        SecretKey secretKey = kg.generateKey();

        // 获得密钥的二进制编码形式

        return secretKey.getEncoded();
    }


    /**
     * 测试
     *
     * @throws Exception
     */
    public final void test() throws Exception {

        String inputStr = "IDEA";
        byte[] inputData = inputStr.getBytes();
        System.err.println("原文:\t" + inputStr);

        // 初始化密钥

        byte[] key = initKey();
        System.err.println("密钥:\t" + Base64.toBase64String(key));

        // 加密

        inputData = encrypt(inputData, key);
        System.err.println("加密后:\t" + Base64.toBase64String(inputData));

        // 解密

        byte[] outputData = decrypt(inputData, key);

        String outputStr = new String(outputData);
        System.err.println("解密后:\t" + outputStr);

        // 校验

        //        assertEquals(inputStr, outputStr);
    }


    public static void main(String[] args) throws Exception {
        String inputStr = "IDEA";
        byte[] inputData = inputStr.getBytes();
        System.err.println("原文:\t" + inputStr);

        // 初始化密钥

        byte[] key = initKey();
        System.err.println("密钥:\t" + Base64.toBase64String(key));

        // 加密

        inputData = encrypt(inputData, key);
        System.err.println("加密后:\t" + Base64.toBase64String(inputData));

        // 解密

        byte[] outputData = decrypt(inputData, key);

        String outputStr = new String(outputData);
        System.err.println("解密后:\t" + outputStr);
    }
}
